<script setup lang="ts">
import { Reads, Writes } from '@/Utils/axiosHelper'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

// Router instance
const router = useRouter()

// Form data - matching C# model structure
const formData = ref({
  earSignal: '',
  electronicEarTag: '',
  fatherNumber: null as number | null,
  motherEarTag: null as number | null,
  variety: null as number | null,
  gender: null as number | null,
  birthStatus: null as number | null,
  dateofBirth: '',
  entryDate: '',
  placeOfBirth: null as number | null,
  birthWeight: null as number | null,
  geneRank: null as number | null,
  note: ''
})

// Validation state
const validationErrors = ref<Record<string, string>>({})

// Validation rules
const validateField = (field: string, value: any, required = false): string => {
  if (required && (!value || value === '')) {
    return '此字段不能为空'
  }
  return ''
}

const validateForm = (): boolean => {
  const errors: Record<string, string> = {}
  
  // Required field validations
  errors.earSignal = validateField('earSignal', formData.value.earSignal, true)
  errors.electronicEarTag = validateField('electronicEarTag', formData.value.electronicEarTag, true)
  errors.fatherNumber = validateField('fatherNumber', formData.value.fatherNumber, true)
  errors.motherEarTag = validateField('motherEarTag', formData.value.motherEarTag, true)
  errors.variety = validateField('variety', formData.value.variety, true)
  errors.gender = validateField('gender', formData.value.gender, true)
  errors.birthStatus = validateField('birthStatus', formData.value.birthStatus, true)
  errors.dateofBirth = validateField('dateofBirth', formData.value.dateofBirth, true)
  errors.entryDate = validateField('entryDate', formData.value.entryDate, true)
  errors.placeOfBirth = validateField('placeOfBirth', formData.value.placeOfBirth, true)
  errors.birthWeight = validateField('birthWeight', formData.value.birthWeight, true)
  errors.geneRank = validateField('geneRank', formData.value.geneRank, true)
  
  validationErrors.value = errors
  
  // Check if there are any errors
  return Object.values(errors).every(error => error === '')
}

// Dropdown options with ID mappings (matching C# model)
const birthStatusOptions = [
  { id: 1, name: '健羔' },
  { id: 2, name: '弱羔' },
  { id: 3, name: '畸形' },
  { id: 4, name: '死胎' },
  { id: 5, name: '木乃伊' },
  { id: 6, name: '畸胎' }
]

const varietyOptions = [
  { id: 1, name: '萨福克' },
  { id: 2, name: '多赛特' },
  { id: 3, name: '美利奴' },
  { id: 4, name: '波尔山羊' },
  { id: 5, name: '其他' }
]

const genderOptions = [
  { id: 1, name: '公' },
  { id: 2, name: '母' }
]

const geneRankOptions = [
  { id: 1, name: '一级' },
  { id: 2, name: '二级' },
  { id: 3, name: '三级' },
  { id: 4, name: '四级' }
]

const fatherNumberOptions = [
  { id: 1, name: 'F001' },
  { id: 2, name: 'F002' },
  { id: 3, name: 'F003' }
]

const motherEarTagOptions = [
  { id: 1, name: 'M001' },
  { id: 2, name: 'M002' },
  { id: 3, name: 'M003' }
]

const placeOfBirthOptions = [
  { id: 1, name: '场地A' },
  { id: 2, name: '场地B' },
  { id: 3, name: '场地C' }
]

// Action handlers
const handleAdd = () => {
  console.log('新增 livestock record')
  // Reset form or add new record logic
}

const handleSave = async () => {
  // Step 1: Validate form before any API calls
  if (!validateForm()) {
    // Collect all missing fields for user feedback
    const missingFields = []
    const fieldNames = {
      earSignal: '耳号',
      electronicEarTag: '电子耳标号',
      fatherNumber: '父耳号',
      motherEarTag: '母耳号',
      variety: '品种',
      gender: '性别',
      birthStatus: '出生状态',
      dateofBirth: '出生日期',
      entryDate: '入场日期',
      placeOfBirth: '出生场地',
      birthWeight: '出生重量',
      geneRank: '基因等级'
    }
    
    for (const [field, name] of Object.entries(fieldNames)) {
      if (validationErrors.value[field]) {
        missingFields.push(name)
      }
    }
    
    // Show comprehensive warning to user
    const message = `请填写以下必填项目：\n\n${missingFields.join('\n')}\n\n请检查标有红色星号(*)的字段。`
    alert(message)
    
    console.warn('表单验证失败，请检查必填字段:', missingFields)
    return // Stop execution if validation fails
  }
  
  // Step 2: Form is valid, prepare data for API
  console.log('表单验证通过，准备保存 livestock record:', formData.value)
  console.log('C# Model Structure:', {
    earSignal: formData.value.earSignal,
    electronicEarTag: formData.value.electronicEarTag,
    fatherNumber: formData.value.fatherNumber,
    motherEarTag: formData.value.motherEarTag,
    variety: formData.value.variety,
    gender: formData.value.gender,
    birthStatus: formData.value.birthStatus,
    dateofBirth: formData.value.dateofBirth,
    entryDate: formData.value.entryDate,
    placeOfBirth: formData.value.placeOfBirth,
    birthWeight: formData.value.birthWeight,
    geneRank: formData.value.geneRank,
    note: formData.value.note
  })
  
  try {
    // Step 3: Make API call with proper error handling
    const response = await Writes.post('/Management/CreatedDescendant', formData.value, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    console.log('API Response:', response)
    
    // Step 4: Handle API response
    if (response.data && response.data.code === 100) {
      alert('新增成功！。')
      router.push('/descendant-list')
      // Optional: Reset form after successful save
      // resetForm()
    } else {
      // Handle API success but business logic failure
      const errorMsg = response.data?.message || '服务器返回错误，请稍后重试'
      alert(`保存失败：${errorMsg}`)
      console.error('API业务逻辑错误:', response.data)
    }
    
  } catch (error: unknown) {
    // Step 5: Handle network/API errors
    console.error('API调用失败:', error)
    
    let errormessage = '网络错误或服务器异常，请检查网络连接后重试'
    
    // Handle different types of errors
    if (error instanceof Error) {
      // Check if it's an Axios error by looking for axios-specific properties
      const axiosError = error as any;
      if (axiosError.response) {
        // Server responded with error status
        errormessage = (axiosError.response.data as any)?.message || `服务器错误 (${axiosError.response.status})`
      } else if (axiosError.request) {
        // Request made but no response received
        errormessage = '无法连接到服务器，请检查服务器是否运行'
      } else {
        // Non-Axios error, use the message if available
        errormessage = error.message || errormessage
      }
    }
    
    alert(`保存失败：${errormessage}`)
  }
}

const handleUndo = () => {
  console.log('撤销 changes')
  // Reset form to previous state logic
}

const handleDelete = () => {
  console.log('删除 livestock record')
  // Delete record logic
}

const navigateToList = () => {
  router.push('/descendant-list')
}
</script>

<template>
  <main class="livestock-management">
    <!-- Action Buttons -->
    <div class="action-buttons">
      <button type="button" class="btn btn-red" @click="handleAdd">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
        </svg>
        新增
      </button>
      <button type="button" class="btn btn-red" @click="handleSave">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"/>
        </svg>
        保存
      </button>
      <button type="button" class="btn btn-red" @click="handleUndo">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z"/>
        </svg>
        撤销
      </button>
      <button type="button" class="btn btn-red" @click="handleDelete">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
        </svg>
        删除
      </button>
      <button type="button" class="btn btn-red" @click="navigateToList">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z"/>
        </svg>
        列表
      </button>
    </div>

    <!-- Basic Information Form -->
    <div class="form-section">
      <h3>基本信息</h3>
      <form class="livestock-form">
        <!-- Row 1: EarSignal, ElectronicEarTag, FatherNumber -->
        <div class="form-row">
          <div class="form-group">
              <label for="earSignal">耳号 <span class="required">*</span></label>
              <input 
                id="earSignal"
                v-model="formData.earSignal" 
                type="text" 
                class="form-control"
                :class="{ 'is-invalid': validationErrors.earSignal }"
                placeholder="请输入耳号"
              >
              <div v-if="validationErrors.earSignal" class="invalid-feedback">
                {{ validationErrors.earSignal }}
              </div>
            </div>
          <div class="form-group">
              <label for="electronicEarTag">电子耳标号 <span class="required">*</span></label>
              <input 
                id="electronicEarTag"
                v-model="formData.electronicEarTag" 
                type="text" 
                class="form-control"
                :class="{ 'is-invalid': validationErrors.electronicEarTag }"
                placeholder="请输入电子耳标号"
              >
              <div v-if="validationErrors.electronicEarTag" class="invalid-feedback">
                {{ validationErrors.electronicEarTag }}
              </div>
            </div>
          <div class="form-group">
            <label for="fatherNumber">父耳号 <span class="required">*</span></label>
            <select id="fatherNumber" v-model="formData.fatherNumber" class="form-control" :class="{ 'is-invalid': validationErrors.fatherNumber }">
              <option value="">请选择父耳号</option>
              <option v-for="option in fatherNumberOptions" :key="option.id" :value="option.id">{{ option.name }}</option>
            </select>
            <div v-if="validationErrors.fatherNumber" class="invalid-feedback">
              {{ validationErrors.fatherNumber }}
            </div>
          </div>
        </div>

        <!-- Row 2: MotherEarTag, Variety, Gender -->
        <div class="form-row">
          <div class="form-group">
            <label for="motherEarTag">母耳号 <span class="required">*</span></label>
            <select id="motherEarTag" v-model="formData.motherEarTag" class="form-control" :class="{ 'is-invalid': validationErrors.motherEarTag }">
              <option value="">请选择母耳号</option>
              <option v-for="option in motherEarTagOptions" :key="option.id" :value="option.id">{{ option.name }}</option>
            </select>
            <div v-if="validationErrors.motherEarTag" class="invalid-feedback">
              {{ validationErrors.motherEarTag }}
            </div>
          </div>
          <div class="form-group">
            <label for="variety">品种 <span class="required">*</span></label>
            <select id="variety" v-model="formData.variety" class="form-control" :class="{ 'is-invalid': validationErrors.variety }">
              <option value="">请选择品种</option>
              <option v-for="option in varietyOptions" :key="option.id" :value="option.id">{{ option.name }}</option>
            </select>
            <div v-if="validationErrors.variety" class="invalid-feedback">
              {{ validationErrors.variety }}
            </div>
          </div>
          <div class="form-group">
            <label for="gender">性别 <span class="required">*</span></label>
            <select id="gender" v-model="formData.gender" class="form-control" :class="{ 'is-invalid': validationErrors.gender }">
              <option value="">请选择性别</option>
              <option v-for="option in genderOptions" :key="option.id" :value="option.id">{{ option.name }}</option>
            </select>
            <div v-if="validationErrors.gender" class="invalid-feedback">
              {{ validationErrors.gender }}
            </div>
          </div>
        </div>

        <!-- Row 3: BirthStatus, DateofBirth, EntryDate -->
        <div class="form-row">
          <div class="form-group">
            <label for="birthStatus">出生状态 <span class="required">*</span></label>
            <select id="birthStatus" v-model="formData.birthStatus" class="form-control" :class="{ 'is-invalid': validationErrors.birthStatus }">
              <option value="">请选择出生状态</option>
              <option v-for="option in birthStatusOptions" :key="option.id" :value="option.id">{{ option.name }}</option>
            </select>
            <div v-if="validationErrors.birthStatus" class="invalid-feedback">
              {{ validationErrors.birthStatus }}
            </div>
          </div>
          <div class="form-group">
            <label for="dateofBirth">出生日期 <span class="required">*</span></label>
            <input 
                id="dateofBirth"
                v-model="formData.dateofBirth" 
                type="date" 
                class="form-control"
                :class="{ 'is-invalid': validationErrors.dateofBirth }"
              >
              <div v-if="validationErrors.dateofBirth" class="invalid-feedback">
                {{ validationErrors.dateofBirth }}
              </div>
          </div>
          <div class="form-group">
            <label for="entryDate">入场日期 <span class="required">*</span></label>
            <input 
                id="entryDate"
                v-model="formData.entryDate" 
                type="date" 
                class="form-control"
                :class="{ 'is-invalid': validationErrors.entryDate }"
              >
              <div v-if="validationErrors.entryDate" class="invalid-feedback">
                {{ validationErrors.entryDate }}
              </div>
          </div>
        </div>

        <!-- Row 4: PlaceOfBirth, BirthWeight, GeneRank -->
        <div class="form-row">
          <div class="form-group">
            <label for="placeOfBirth">出生场地 <span class="required">*</span></label>
            <select id="placeOfBirth" v-model="formData.placeOfBirth" class="form-control" :class="{ 'is-invalid': validationErrors.placeOfBirth }">
              <option value="">请选择出生场地</option>
              <option v-for="option in placeOfBirthOptions" :key="option.id" :value="option.id">{{ option.name }}</option>
            </select>
            <div v-if="validationErrors.placeOfBirth" class="invalid-feedback">
              {{ validationErrors.placeOfBirth }}
            </div>
          </div>
          <div class="form-group">
            <label for="birthWeight">出生重量 <span class="required">*</span></label>
            <input 
                id="birthWeight"
                v-model="formData.birthWeight" 
                type="number" 
                step="1"
                class="form-control"
                :class="{ 'is-invalid': validationErrors.birthWeight }"
                placeholder="请输入出生重量"
              >
              <div v-if="validationErrors.birthWeight" class="invalid-feedback">
                {{ validationErrors.birthWeight }}
              </div>
          </div>
          <div class="form-group">
            <label for="geneRank">基因等级 <span class="required">*</span></label>
            <select id="geneRank" v-model="formData.geneRank" class="form-control" :class="{ 'is-invalid': validationErrors.geneRank }">
              <option value="">请选择基因等级</option>
              <option v-for="option in geneRankOptions" :key="option.id" :value="option.id">{{ option.name }}</option>
            </select>
            <div v-if="validationErrors.geneRank" class="invalid-feedback">
              {{ validationErrors.geneRank }}
            </div>
          </div>
        </div>

        <!-- Row 5: Note -->
        <div class="form-row">
          <div class="form-group full-width">
            <label for="note">备注</label>
            <textarea 
                id="note"
                v-model="formData.note" 
                class="form-control"
                rows="4"
                placeholder="请输入备注信息"
              ></textarea>
          </div>
        </div>
      </form>
    </div>
  </main>
</template>

<style scoped>
.livestock-management {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #e9ecef;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  min-width: 100px;
  justify-content: center;
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
}

.btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(220, 53, 69, 0.2);
}

.btn-red {
  background: linear-gradient(135deg, #dc3545, #c82333);
  color: white;
  border: 1px solid #bd2130;
}

.btn-red:hover {
  background: linear-gradient(135deg, #c82333, #bd2130);
  box-shadow: 0 4px 12px rgba(220, 53, 69, 0.4);
}

.btn-icon {
  width: 18px;
  height: 18px;
  flex-shrink: 0;
}

.form-section {
  background: white;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.form-section h3 {
  margin-bottom: 25px;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.livestock-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* Validation styles */
.required {
  color: #dc3545;
  font-weight: bold;
}

.is-invalid {
  border-color: #dc3545 !important;
  box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25) !important;
}

.invalid-feedback {
  display: block;
  width: 100%;
  margin-top: 0.25rem;
  font-size: 0.875rem;
  color: #dc3545;
  font-weight: 500;
}

.form-control {
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.form-control:focus {
  border-color: #80bdff;
  outline: 0;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.form-control.is-invalid:focus {
  border-color: #dc3545;
  box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
}

.form-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  margin-bottom: 8px;
  font-weight: 500;
  color: #555;
  font-size: 14px;
}

.form-control {
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.form-control:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
}

.form-control::placeholder {
  color: #999;
}

select.form-control {
  cursor: pointer;
}

textarea.form-control {
  resize: vertical;
  min-height: 100px;
}

@media (max-width: 768px) {
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-wrap: wrap;
  }
  
  .btn {
    flex: 1;
    min-width: 120px;
  }
}
</style>
